//
//  MainViewController.m
//  最牛新闻
//
//  Created by 自娱自乐自逍遥 on 15-1-31.
//  Copyright (c) 2015年 wdj. All rights reserved.
//

#import "MainViewController.h"
#import "TouchPropagatedScrollView.h"
#import "DBImageView.h"
#import "WebViewController.h"

#define MENU_BUTTON_WIDTH 60

@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>{
    UIScrollView *_scrollV;
    UIScrollView *_contentScrollView;
    NSInteger _currentCategory;
    NSDictionary *_categoryInfos;
    NSMutableDictionary *_newsDatas;
    NSOperationQueue *_queue;
    NSArray *_categoryValues ;
}

@property(nonatomic, strong)MBProgressHUD *hud;

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIBarButtonItem *refresh = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshData:)];
        refresh.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = refresh;
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"最Low新闻"];
    [DBImageView setAnimationsEnabled:YES];
    
    NSArray *categorys = @[@"推荐",@"社会",@"娱乐",@"体育",@"逗比",@"军事",@"闺房",@"健康",@"美女",@"科技",@"IT"];
    _categoryValues = @[@"100",@"1192652582",@"179223212",@"923258246",@"1670553277",@"1105405272",@"1099189934",@"1099189934",@"1404457531633",@"1525483516",@"242677432"];

    _scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    [_scrollV setShowsHorizontalScrollIndicator:NO];
    
    _contentScrollView = [[UIScrollView alloc]initWithFrame:
                          CGRectMake(0,
                                     _scrollV.frame.size.height,
                                     self.view.bounds.size.width,
                                     CGRectGetHeight(self.view.bounds) - CGRectGetHeight(_scrollV.frame) - self.navigationController.navigationBar.frame.size.height
                                     )];
    _contentScrollView.backgroundColor = [UIColor orangeColor];
    _contentScrollView.pagingEnabled = YES;
    _contentScrollView.showsHorizontalScrollIndicator = NO;
    _contentScrollView.delegate = self;
    _contentScrollView.directionalLockEnabled = YES;

    for (int i = 0; i < categorys.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(i * 60, 0, 60, 40)];
        [btn setTitle:categorys[i] forState:UIControlStateNormal];
        [btn setTag: i + 1];
        [btn addTarget:self action:@selector(actionbtn:) forControlEvents:UIControlEventTouchUpInside];
        
        if (0 == i) {
            [self changeColorForButton:btn red:1];
        }else{
            [self changeColorForButton:btn red:0];
        }
        
        [_scrollV addSubview: btn];
        
        UITableView *table = [[UITableView alloc]initWithFrame:CGRectMake(i*self.view.bounds.size.width, 0, self.view.bounds.size.width, CGRectGetHeight(_contentScrollView.bounds))];
        table.tag = i + 1;
        
        table.dataSource = self;
        table.delegate = self;
        
        
        UIView *bg = [[UIView alloc]initWithFrame:table.bounds];
        
        UILabel *refreshLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(table.bounds), 30)];
        refreshLabel.text = @"下拉刷新";
        refreshLabel.textAlignment = NSTextAlignmentCenter;
        refreshLabel.textColor = [UIColor blueColor];
        refreshLabel.center = CGPointMake(CGRectGetMidX(table.bounds), 30);
        refreshLabel.font = [UIFont systemFontOfSize:14];
        refreshLabel.tag = 99;
        refreshLabel.layer.opacity = 0;
        
        [bg addSubview:refreshLabel];
        
        table.backgroundView = bg;
        
        [_contentScrollView addSubview: table];
    }
    
    [_scrollV setContentSize: CGSizeMake(categorys.count * 60, 40)];
    [_scrollV setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview: _scrollV];

    [_contentScrollView setContentSize:CGSizeMake(categorys.count * _contentScrollView.frame.size.width, _contentScrollView.frame.size.width)];
    [self.view insertSubview:_contentScrollView belowSubview:_scrollV];

    
    
    _hud = [[MBProgressHUD alloc]initWithView:self.view];

    [self.view addSubview: _hud];
    
    UIButton *firstBtn = (UIButton *)[_scrollV viewWithTag:1];
    [self actionbtn:firstBtn];
}

- (void)refreshData:(id)sender{
    [_newsDatas setValue:nil forKey: [[NSNumber numberWithLong:_currentCategory] stringValue]];
    UIButton *btn = (UIButton *)[_scrollV viewWithTag:_currentCategory + 1];
    [self actionbtn:btn];
}

- (void)actionbtn:(UIButton *)btn
{
    [_scrollV scrollRectToVisible:CGRectMake((btn.tag - 1) * MENU_BUTTON_WIDTH - CGRectGetMidX(self.view.bounds) + CGRectGetWidth(btn.bounds)/2, 0, _scrollV.frame.size.width, _scrollV.frame.size.height) animated:YES];
    
    [_contentScrollView scrollRectToVisible:CGRectMake((btn.tag - 1) *  _contentScrollView.frame.size.width, _contentScrollView.frame.origin.y, _contentScrollView.frame.size.width, _contentScrollView.frame.size.height) animated:YES];
    
    for (UIButton *b in _scrollV.subviews) {
        [self changeColorForButton:b red:0];
    }
    
    [self changeColorForButton:btn red:1];
    _currentCategory = btn.tag - 1;
    
    [self loadData:btn];
}

- (void)changeColorForButton:(UIButton *)btn red:(float)nRedPercent
{
    if (nRedPercent) {
        [btn setBackgroundColor:[UIColor redColor]];
        btn.layer.cornerRadius = 10;
        btn.layer.borderWidth = 5;
        btn.layer.borderColor = [UIColor grayColor].CGColor;
    }else{
        [btn setBackgroundColor:[UIColor clearColor]];
    }
}

- (void)loadData:(UIButton *)btn{
    if (!_newsDatas) {
        _newsDatas = [[NSMutableDictionary alloc]initWithCapacity:12];
    }
    
    NSArray *categoryData = [_newsDatas objectForKey:[NSString stringWithFormat:@"%li",(long)_currentCategory ]];
    
    if (!categoryData) {
        NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://zzd.sm.cn/webapp/api/v1/channel/%@?method=new&ftime=0&count=20&summary=0&content_cnt=0&recoid=&sn=f691e675636c9fd17052da7090352334&client_os=webapp&client_version=1.7.0.0&bid=800&m_ch=010&city=&_=1422770005265", _categoryValues[_currentCategory]]]];
        
        if (!_queue) {
            _queue = [[NSOperationQueue alloc]init];
            [_queue setMaxConcurrentOperationCount:5];
        }
        
        [_hud setMode: MBProgressHUDModeIndeterminate];
        _hud.labelText = @"玩命加载中...";
        [_hud show:YES];
        [_hud hide:YES afterDelay:10];
        
        [NSURLConnection sendAsynchronousRequest:req queue:_queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            if (data) {
                NSDictionary *rt = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                
                [_newsDatas setValue:rt[@"data"][@"article"] forKey:[[NSNumber numberWithLong:_currentCategory] stringValue]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    UITableView *t = (UITableView *)[_contentScrollView viewWithTag:btn.tag];
                    [t reloadData];
                    [t setContentOffset:CGPointMake(0, 0) animated:YES];
                    [_hud hide:YES];
                });
            }
            if (connectionError) {
                _hud.labelText = @"加载失败,刷新试试!";
                [_hud setMode: MBProgressHUDModeText];
                [_hud hide:YES afterDelay:2];
            }
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark tableView 

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *bg = [[UIView alloc]init];
    [bg setBackgroundColor:[UIColor whiteColor]];
    return bg;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *categoryData = [_newsDatas objectForKey:[[NSNumber numberWithLong:_currentCategory] stringValue]];
    return [categoryData count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return _currentCategory == 4 ? 303 : 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *categoryData = [_newsDatas objectForKey:[[NSNumber numberWithLong:_currentCategory] stringValue]];
    NSDictionary *row = categoryData[indexPath.row];
    NSString *url = [NSString stringWithFormat:@"http://zzd.sm.cn/webapp/webview/article/%@?cid=%@&from=smhome&uc_param_str=dncpeiwi",row[@"id"], row[@"cid"]];
    
    WebViewController *webC = [[WebViewController alloc]init];
    webC.url = [NSURL URLWithString: url];
    [webC setTitle:@"新闻详情"];
    [self.navigationController pushViewController:webC animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *categoryData = [_newsDatas objectForKey:[[NSNumber numberWithLong:_currentCategory] stringValue]];
    NSDictionary *row = categoryData[indexPath.row];
    UITableViewCell *cell;
    
    if (_currentCategory == 4) {
        NSString *identifer = @"doubicell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DouBiTableViewCell" owner:self options:nil]lastObject];
            [cell setSeparatorInset:UIEdgeInsetsZero];
            UIView *v = [cell viewWithTag:103];
            
            DBImageView *imgView = [[DBImageView alloc]initWithFrame: v.frame];
            [imgView setPlaceHolder:[UIImage imageNamed:@"placeholder.png"]];
            imgView.tag = v.tag;
            [cell addSubview:imgView];
            [v removeFromSuperview];
        }
        DBImageView *img = (DBImageView *)[cell viewWithTag:103];
        NSString *imgURL = [[[row objectForKey:@"thumbnails"]firstObject]objectForKey:@"url"];
        [img setImageWithPath: imgURL];
        
        UILabel *title = (UILabel *)[cell viewWithTag:101];
        [title setText:row[@"summary"]];
        
        UILabel *attr = (UILabel *)[cell viewWithTag:102];
        [attr setText: [NSString stringWithFormat:@"14分钟前 阅读:%@", row[@"comment_cnt"]]];
        
        UILabel *imgCount = (UILabel *)[cell viewWithTag:104];
        [imgCount setText: [NSString stringWithFormat:@"%@",[NSNumber numberWithUnsignedInteger:[row[@"image"]count]]]];
        
    }else{
        NSString *identifer = @"cell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:self options:nil]lastObject];
            [cell setSeparatorInset:UIEdgeInsetsZero];
            UIView *v = [cell viewWithTag:103];
            
            DBImageView *imgView = [[DBImageView alloc]initWithFrame: v.frame];
            [imgView setPlaceHolder:[UIImage imageNamed:@"placeholder.png"]];
            imgView.tag = v.tag;
            [cell addSubview:imgView];
            [v removeFromSuperview];
        }
        
        UILabel *title = (UILabel *)[cell viewWithTag:101];
        [title setText:row[@"title"]];
        
        DBImageView *img = (DBImageView *)[cell viewWithTag:103];
        NSString *imgURL = [[[row objectForKey:@"thumbnails"]firstObject]objectForKey:@"url"];
        [img setImageWithPath: imgURL];
        
        UILabel *attr = (UILabel *)[cell viewWithTag:102];
        [attr setText: [NSString stringWithFormat:@"14分钟前 阅读:%@", row[@"comment_cnt"]]];
    }
    
    return cell;
}

#pragma mark 内容 scrollView

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (![scrollView isKindOfClass: [UITableView class]]) {
        NSInteger p = (NSInteger)round(scrollView.contentOffset.x / scrollView.frame.size.width);
        if (p != _currentCategory) {
            _currentCategory = p;
            UIButton *btn = (UIButton *)[_scrollV viewWithTag:_currentCategory+1];
            [self actionbtn: btn];
        }
    }else{
        
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if ([scrollView isKindOfClass: [UITableView class]]){
        if (scrollView.contentOffset.y < -50) {
            [self refreshData:nil];
        }
        UILabel *label = (UILabel *)[scrollView viewWithTag:99];
        label.text = @"下拉刷新";
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass: [UITableView class]]){
        UILabel *label = (UILabel *)[scrollView viewWithTag:99];
        label.layer.opacity = 1;
        if (scrollView.contentOffset.y < -50) {
            label.text = @"释放刷新";
        }else{
            label.text = @"下拉刷新";
        }
    }
}

@end
